package cn.itcast.servlet.review;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.itcast.service.StudentService;
import cn.itcast.service.TextBookService;
import cn.itcast.service.impl.StudentServiceImpl;
import cn.itcast.service.impl.TextBookServiceImpl;
import cn.itcast.vo.TextBook;

public class FindAllTextBook extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
         
		String id = request.getParameter("token_id");
		StudentService studentService = new StudentServiceImpl();
		String token_id = studentService.getTokenid(id);
		if (token_id == null) {
			JSONObject obj = new JSONObject();
			try {
				obj.put("status", "fail");
				String json = obj.toString();
				System.out.println(json);
				out.write(json);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			TextBookService textBookService = new TextBookServiceImpl();
			List<TextBook> list = textBookService.getAllTextBook();
			JSONObject obj = new JSONObject();
			try {
				obj.put("status", "success");
				JSONArray textBooks = new JSONArray();
				for (TextBook tb : list) {
					JSONObject textBook = new JSONObject();
					textBook.put("id", tb.getId());
					textBook.put("name", tb.getName());
					textBooks.put(textBook);
				}
				obj.put("textBooks", textBooks);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// String json="{\"textBookName\":"+data+"}";
			String json = obj.toString();
			System.out.println(json);
			out.write(json);
		}

	}

}
